﻿
var Application = angular.module("app", [])

Application.service('Parse', [function () {
    Parse.initialize("hoUdUTN3q4Js5lc1YFLNwRMoFiZfKKMbKpOD7E2q", "R69EMYXOUNPkY2Vh78fnayUdflscKqQoOnsmKfUI");

    var Charity = Parse.Object.extend("Charity");
    var queryObject = new Parse.Query(Charity);
    
    return {
        findCherities: function (success) {
            queryObject.find({
                success: function (results) {
                    console.log('Success', results)
                    success(results)
                },
                error: function (error) {
                    alert("Error: " + error.code + " " + error.message);
                }
            })

        },
        createCherity: function (data, callback) {
            var charity = new Charity();
            charity.set("name", data[0])
            charity.set("description", data[1])
            charity.set("followers", 0)

            charity.save(null, {
                success: function (charity) {
                    // Execute any logic that should take place after the object is saved.
                    alert('New object created with objectId: ' + charity.id);
                },
                error: function (charity, error) {
                    // Execute any logic that should take place if the save fails.
                    // error is a Parse.Error with an error code and description.
                    alert('Failed to create new object, with error code: ' + error.description);
                }
            });
        }

    }
}])

Application.controller('CharityLoadCtrl', ['$rootScope', 'Parse', '$scope', function ($rootScope, Parse, $scope) {
    $scope.charities = []
    console.log(Parse.findCherities(function (response) {
        $scope.charities = response
        $scope.$apply()
    }))

    $scope.save = function () {
        Parse.createCherity([$scope.name,CKEDITOR.instances.submitter.getData()], function() { console.log('Data was saved')})
    }
    $scope.follow = function () {
        console.log("followed")
    }

  
}])
Parse.initialize("hoUdUTN3q4Js5lc1YFLNwRMoFiZfKKMbKpOD7E2q", "R69EMYXOUNPkY2Vh78fnayUdflscKqQoOnsmKfUI");
function logout() {
    Parse.User.logOut();
    location.reload();
}
window.onload = function () {
    var currentUser = Parse.User.current();
    if (!currentUser) {
        window.location = "index.html";
    }
    document.getElementById("name").innerHTML = currentUser.getUsername();
}


